const pool = require('../../database');
const fileUpload = require('express-fileupload');
const path = require('path');
const fs = require('fs');
const { promisify } = require('util');
const writeFileAsync = promisify(fs.writeFile);

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}

// 图片上传控制器
exports.uploadImage = async (req, res) => {
  try {
    if (!req.files || Object.keys(req.files).length === 0) {
      return res.status(400).send('没有上传任何文件。');
    }

    // 假设上传的文件字段名为 'image'
    const image = req.files.image;

    // 生成唯一的文件名
    const fileName = `${Date.now()}-${image.name}`;
    const filePath = path.join(uploadDir, fileName);

    // 保存文件到服务器
    await writeFileAsync(filePath, image.data);

    res.status(200).json({
      message: '图片上传成功',
      filePath: `/uploads/${fileName}`
    });
  } catch (err) {
    console.error('图片上传出错:', err);
    res.status(500).json({ error: '图片上传失败' });
  }
};

// 原有的获取食谱列表方法
exports.getRecipes = async (req, res) => {
  try {
    const [rows] = await pool.query(`
      SELECT r.*, 
        GROUP_CONCAT(DISTINCT i.name SEPARATOR ', ') AS ingredients,
        n.calories, n.protein, n.fat, n.carbs
      FROM recipes r
      LEFT JOIN ingredients i ON r.id = i.recipe_id
      LEFT JOIN nutrition n ON r.id = n.recipe_id
      GROUP BY r.id
      LIMIT 20
    `);
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

// 原有的根据 ID 获取食谱方法
exports.getRecipeById = async (req, res) => {
  try {
    const [recipe] = await pool.query('SELECT * FROM recipes WHERE id = ?', [req.params.id]);

    if (!recipe.length) {
      return res.status(404).json({ error: 'Recipe not found' });
    }

    const [ingredients] = await pool.query('SELECT * FROM ingredients WHERE recipe_id = ?', [req.params.id]);
    const [steps] = await pool.query('SELECT * FROM steps WHERE recipe_id = ? ORDER BY step_number', [req.params.id]);
    const [nutrition] = await pool.query('SELECT * FROM nutrition WHERE recipe_id = ?', [req.params.id]);

    res.json({
      ...recipe[0],
      ingredients,
      steps,
      nutrition: nutrition[0] || null
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};
